package moe.loliserver;

import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_16_R3.CraftServer;
import org.bukkit.craftbukkit.v1_16_R3.command.BukkitCommandWrapper;
import org.bukkit.craftbukkit.v1_16_R3.command.VanillaCommandWrapper;

public class CommandDispatcherHook {
    public static <S> void onRegisterPost(RootCommandNode<S> root, CommandNode<S> child) {
        if (Bukkit.getServer() instanceof CraftServer) {
            CraftServer craftServer = (CraftServer) Bukkit.getServer();
            if (craftServer.isVanillaCommandRegistered && !craftServer.isSyncingCommand && !(child.getCommand() instanceof BukkitCommandWrapper)) {
                Commands dispatcher = craftServer.getServer().getCommands();
                RootCommandNode<CommandSource> vanillaRoot = dispatcher.getDispatcher().getRoot();
                if (root == vanillaRoot) {
                    craftServer.getCommandMap().register("minecraft", new VanillaCommandWrapper(dispatcher, (CommandNode<CommandSource>)child));
                }
            }
        }
    }
}
